package fr.inserm.umr915.vcfserver.j2ee;

import java.util.Arrays;


/**
 * Path
 */
public class Path
	{
	private String tokens[];
	private int start;
	private int length;
	
	/**
	 * req.getServletPath()+(req.getPathInfo()!=null?req.getPathInfo()!=null:""))
	 * @param uri
	 */
	public Path(String uri)
		{
		if(uri==null) uri="";
		while(uri.startsWith("/")) uri=uri.substring(1);
		while(uri.endsWith("/")) uri=uri.substring(0,uri.length()-1);
		this.tokens=uri.split("[/]+");
		this.start=0;
		this.length=tokens.length;
		}
	
	
	private Path(String tokens[],int start,int length)
		{
		this.tokens=tokens;
		this.start=start;
		this.length=length;
		}
	
	public int size()
		{
		return length;
		}
	
	public int indexOf(String s)
		{
		for(int i=0;i< size();++i)
			{
			if(get(i).equals(s)) return i;
			}
		return -1;
		}
	
	public String get(int index)
		{
		return(index>=0 && index<this.length?this.tokens[this.start+index]:"");
		}
	public String getString()
		{
		StringBuilder b=new StringBuilder();
		for(int i=0;i< size();++i)
			{
			b.append('/');
			b.append(get(i));
			}
		return b.toString();
		}
	
	@Override
	public boolean equals(Object obj)
		{
		if(obj==this) return true;
		if(obj==null || obj.getClass()!=this.getClass()) return false;
		Path cp=Path.class.cast(obj);
		if(size()!=cp.size()) return false;
		for(int i=0;i< size();++i)
			{
			if(!get(i).equals(cp.get(i))) return false;
			}
		return true;
		}
	
	public String getLast()
		{
		return get(size()-1);
		}
	
	public String getSuffix()
		{
		String s=getLast();
		int i=s.lastIndexOf('.');
		if(i==-1) return "";
		return s.substring(i+1).toLowerCase();
		}
	
	public Path getSubPath(int index)
		{
		int n=this.start+index;
		return new Path(this.tokens,n,size()-n);
		}
	
	@Override
	public int hashCode()
		{
		return Arrays.hashCode(this.tokens);
		}
	
	@Override
	public String toString()
		{
		return getString();
		}
	
	}
